package com.confess.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;
import javax.servlet.http.*;
import net.sf.oval.ConstraintViolation;
import net.sf.oval.Validator;
import net.sf.oval.exception.OValException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.confess.DAO.AnonConfessionDAO;
import com.confess.model.Confession;

@Controller
public class AnonConfessionsHomeController {
	
	@Autowired
	private AnonConfessionDAO dataService;
 
	private static final Logger log = Logger.getLogger(AnonConfessionsHomeController.class.getName());
	
	private Validator validator = new Validator();
	
	@RequestMapping(value="/", method = RequestMethod.GET)
	public String getHome(ModelMap model, HttpSession session) {
		List<Confession> confessions = dataService.getConfessions(0);
		model.addAttribute("confessions",confessions);
		if(!confessions.isEmpty()) {
			session.setAttribute("firstConfDate",confessions.get(0).getDate());
		}
		return "home";
	}
	
	@RequestMapping(value="/submitConfession", method = RequestMethod.POST)
	public String createConfessions(HttpServletRequest req,ModelMap model) throws Exception {
		Confession confession = new Confession();
		Date date = new Date();

		//set the confession
		confession.setDate(date);
		confession.setConfessionBody(req.getParameter("confession"));
		
		if(confession.getConfessionBody().matches(".*(#|/|\\||\\+|\\\\|\"|<|>)+.*")) {
		  throw new Exception("Invalid Format");
		}
		
		// collect the constraint violations
		List<ConstraintViolation> violations = validator.validate(confession);
		
		if(violations.size()>0)
		{
			log.severe("Object " + confession + " is invalid.");
			throw new OValException("Invalid Entry!");
		}
		
		dataService.storeConfession(confession);
		
		//return to jsp page, configured in mvc-dispatcher-servlet.xml, view resolver
		model.addAttribute("confessions",dataService.getConfessions(0));
		return "home";
	}
	
	@RequestMapping(value="/page/{pageNum}", method = RequestMethod.GET)
	public String getNewPage(@PathVariable int pageNum, ModelMap model, HttpServletResponse response) throws IOException {
		PrintWriter out = response.getWriter();
		String resp = "";
		
		List<Confession> nextConfessions = dataService.getConfessions(pageNum);
		
		resp = createResponseString(nextConfessions,resp);
		
		out.write(resp);
		out.close();
		
		model.addAttribute("confessions",dataService.getConfessions(0));
		
		return "home";
	}
	
	@RequestMapping(value="/updateConfessions/", method = RequestMethod.GET)
	public String getNewConfessions(ModelMap model, HttpServletResponse response, HttpSession session) throws IOException {
		PrintWriter out = response.getWriter();
		String resp = "";
		Date firstConfessionDate = (Date) session.getAttribute("firstConfDate");
		List<Confession> newConfessions = dataService.getNewConfessions(firstConfessionDate);
		
		resp = createResponseString(newConfessions,resp);
		
		out.write(resp);
		out.close();
		
		List<Confession> confessions = dataService.getConfessions(0);
		
		model.addAttribute("confessions",confessions);
		
		if(!confessions.isEmpty()) {
			session.setAttribute("firstConfDate",confessions.get(0).getDate());
		}
		return "home";
	}
	
	private int count = 0;
	
	private String createResponseString(List<Confession> confessions, String resp) {
		for (Confession confess : confessions) {
			resp += "<div class='confession' id='newConfession'>";
			resp += "<div id='postitContainer'>";
			if (count == 0) {
				resp += "<a id='postitYellow'>";
				count += 1;
			}else if (count == 1){
				resp += "<a id='postitPink'>";
				count += 1;
			}else if (count == 2){
				resp += "<a id='postitBlue'>";
				count += 1;
			}else if (count == 3){
				resp += "<a id='postitGreen'>";
				count += 1;
			}else if (count == 4){
				resp += "<a id='postitOrange'>";
				count += 1;
			}
			resp += "<p>"+confess.getConfessionBody()+"</p></a>";
			resp += "</div></div>";
			
			if(count == 5)
				count = 0;
		}
		System.out.println(resp);
		return resp;
	}

	public AnonConfessionDAO getDataService() {
		return dataService;
	}

	public void setDataService(AnonConfessionDAO dataService) {
		this.dataService = dataService;
	}
	
	
}